import { useState, useContext, useEffect } from "react";
import UserService from "@/services/user";
import { motion } from "framer-motion";
import { cn } from "@/lib/utils";
import { useTheme } from "@/hooks/useTheme";
import { toast } from "sonner";
import { AuthContext } from "@/App";
import { useNavigate } from "react-router-dom";
import api, { ApiResponse } from '@/services/api';
import { iconOptions } from '@/lib/constants';

const features = [
              {
                icon: "fa-solid fa-file-code",
                title: "专业文档编辑",
                description: "支持Markdown和富文本编辑，轻松创建专业API文档"
              },
              {
                icon: "fa-solid fa-share-nodes",
                title: "团队协作",
                description: "多人实时协作，共同维护API文档"
              },
              {
                icon: "fa-solid fa-diagram-project",
                title: "项目管理",
                description: "结构化组织API文档，清晰管理项目"
              },
              {
                icon: "fa-solid fa-robot",
                title: "智能补全",
                description: "自动补全API参数和代码片段，提升编写效率"
              },
              {
                icon: "fa-solid fa-code-branch",
                title: "版本控制",
                description: "完整的历史记录和版本回溯，轻松管理变更"
              }
];

// 代码片段示例
const codeSnippets = [
  `// 获取用户信息
async function getUser(id) {
  const res = await fetch(\`/api/users/\${id}\`);
  return res.json();
}`,
  `// React组件示例
function Welcome() {
  return <h1>Hello, world!</h1>;
}`,
  `// 计算斐波那契数列
function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}`
];

// 技术栈图标
const techStack = [
  { icon: "fa-brands fa-js", name: "JavaScript" },
  { icon: "fa-brands fa-react", name: "React" },
  { icon: "fa-brands fa-node-js", name: "Node.js" },
  { icon: "fa-brands fa-python", name: "Python" },
  { icon: "fa-brands fa-java", name: "Java" },
  { icon: "fa-brands fa-git-alt", name: "Git" },
  { icon: "fa-brands fa-docker", name: "Docker" },
  { icon: "fa-brands fa-aws", name: "AWS" }
];

export default function Home() {
  const navigate = useNavigate();
  const { theme, isDark, toggleTheme } = useTheme();
  const { isAuthenticated, userInfo, logout } = useContext(AuthContext);
  const [showRegister, setShowRegister] = useState(false);
  const [registerForm, setRegisterForm] = useState({
    userName: '',
    account: '',
    password: '',
    userIcon: 'fa-solid fa-user'
  });
  const [isRegistering, setIsRegistering] = useState(false);
  const [currentCodeIndex, setCurrentCodeIndex] = useState(0);
  const [typingText, setTypingText] = useState("");
  const [isTyping, setIsTyping] = useState(true);

  // 打字机效果
  useEffect(() => {
    const fullText = codeSnippets[currentCodeIndex];
    let i = 0;
    let timer: any;

    const type = () => {
      if (i < fullText.length) {
        setTypingText(fullText.substring(0, i + 1));
        i++;
        timer = setTimeout(type, Math.random() * 50 + 50);
      } else {
        setIsTyping(false);
        setTimeout(() => {
          setIsTyping(true);
          setCurrentCodeIndex((prev) => (prev + 1) % codeSnippets.length);
        }, 2000);
      }
    };

    if (isTyping) {
      type();
    }

    return () => clearTimeout(timer);
  }, [currentCodeIndex, isTyping]);

  const handleRegister = async () => {
    if (!registerForm.userName.trim() || !registerForm.account.trim() || !registerForm.password) {
      toast.error('请填写完整信息');
      return;
    }

    setIsRegistering(true);
    try {
      const res = await UserService.addUser({
        userName: registerForm.userName,
        userIcon: registerForm.userIcon,
        account: registerForm.account,
        password: registerForm.password
      });

      if (res.success) {
        toast.success('注册成功', {
          action: {
            label: '立即登录',
            onClick: () => {
              setShowRegister(false);
              setTimeout(() => {
                navigate('/login');
              }, 500);
            }
          },
          cancel: {
            label: '稍后登录',
            onClick: () => {}
          }
        });
        
        setShowRegister(false);
        setRegisterForm({
          userName: '',
          account: '',
          password: '',
          userIcon: 'fa-solid fa-user'
        });
      } else {
        toast.error(res.data?.message || '注册失败');
      }
    } catch (error: any) {
      console.error('注册错误:', error);
      toast.error(error.response?.data?.message || '注册过程中发生错误');
    } finally {
      setIsRegistering(false);
    }
  };

  // 程序员彩蛋
  const showEasterEgg = () => {
    toast.info("console.log('Hello, Developer!')", {
      duration: 3000,
      position: 'top-center',
      icon: <i className="fa-solid fa-code text-blue-500"></i>
    });
    console.log("%c欢迎开发者!", "color: #3b82f6; font-size: 20px; font-weight: bold");
  };

  return (
      <div className={cn(
        "min-h-screen flex flex-col relative overflow-hidden",
        isDark ? "text-gray-100" : "text-gray-900"
      )}>
        {/* 多彩背景元素 */}
        <div className="absolute inset-0 -z-10 overflow-hidden">
          {/* 主背景渐变 */}
          <div className={cn(
            "absolute inset-0",
            isDark 
              ? "bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900" 
              : "bg-gradient-to-br from-pink-100/70 via-blue-100/50 to-purple-100/60"
          )}></div>
          
          {/* 流动线条装饰 */}
          <svg 
            className="absolute inset-0 w-full h-full opacity-20 dark:opacity-10"
            preserveAspectRatio="none" 
            viewBox="0 0 1200 800"
          >
            <path 
              d="M0,200 C150,100 450,300 600,200 C750,100 900,300 1200,200 L1200,800 L0,800 Z" 
              fill={isDark ? "url(#darkGradient)" : "url(#lightGradient)"}
            ></path>
            <path 
              d="M0,400 C150,300 450,500 600,400 C750,300 900,500 1200,400 L1200,800 L0,800 Z" 
              fill={isDark ? "url(#darkGradient2)" : "url(#lightGradient2)"}
              opacity="0.7"
            ></path>
            
            <defs>
              {/* 暗色模式渐变 */}
              <linearGradient id="darkGradient" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stopColor="#4f46e5" />
                <stop offset="50%" stopColor="#9333ea" />
                <stop offset="100%" stopColor="#db2777" />
              </linearGradient>
              <linearGradient id="darkGradient2" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stopColor="#7c3aed" />
                <stop offset="100%" stopColor="#10b981" />
              </linearGradient>
              
              {/* 亮色模式渐变 */}
              <linearGradient id="lightGradient" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stopColor="#818cf8" />
                <stop offset="50%" stopColor="#c084fc" />
                <stop offset="100%" stopColor="#f472b6" />
              </linearGradient>
              <linearGradient id="lightGradient2" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stopColor="#a78bfa" />
                <stop offset="100%" stopColor="#34d399" />
              </linearGradient>
            </defs>
          </svg>
        </div>
      {/* 导航栏 */}
      <header className={cn(
        "sticky top-0 z-10 p-2 border-b",
        isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
      )}>
        <div className="container mx-auto flex justify-between items-center">
          <motion.div 
            className="flex items-center space-x-2"
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.5 }}
          >
            <button 
              onClick={() => navigate("/")}
              className="flex items-center space-x-2 group"
            >
              <i className="fa-solid fa-file-code text-2xl text-blue-500 group-hover:text-blue-600 transition-colors"></i>
              <motion.h1 
                className="font-mono font-bold text-xl group-hover:text-blue-600 transition-colors"
                whileHover={{ scale: 1.05 }}
              >
                API Docs
              </motion.h1>
            </button>
          </motion.div>
          <div className="flex items-center space-x-4">
            {/* 只在未登录时显示注册按钮 */}
            {!isAuthenticated && (
              <motion.button 
                onClick={() => setShowRegister(true)}
                className={cn(
                  "px-4 py-2 rounded-md font-medium",
                  isDark 
                    ? "bg-blue-600 hover:bg-blue-700" 
                    : "bg-orange-500 hover:bg-orange-600",
                  "text-white"
                )}
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
              >
                <i className="fa-solid fa-user-plus mr-2"></i>
                注册
              </motion.button>
            )}
            <motion.button 
              onClick={toggleTheme}
              className={cn(
                "w-10 h-10 rounded-full flex items-center justify-center",
                isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
              )}
              whileHover={{ rotate: 15 }}
            >
              <i className={isDark ? "fa-solid fa-sun" : "fa-solid fa-moon"}></i>
            </motion.button>

            <div className="relative group">
              {isAuthenticated ? (
                <>
                  <button className="flex items-center space-x-2 px-3 py-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                    <div className="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center">
                      <i className={`${userInfo?.userIcon || "fa-solid fa-user"} text-white text-sm`}></i>
                    </div>
                    <span className="text-sm font-medium">{userInfo?.userName || '用户'}</span>
                    <i className="fa-solid fa-chevron-down text-xs text-gray-500"></i>
                  </button>
                  <div className="absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 invisible group-hover:visible transition-all">
                    <div className="py-1">
                      <div className="px-4 py-2 text-sm text-gray-700 dark:text-gray-200 border-b border-gray-200 dark:border-gray-700">
                        <div className="font-medium">{userInfo?.userName || '用户'}</div>
                        <div className="text-xs text-gray-500">{userInfo?.account || ''}</div>
                      </div>
                      <button 
                        onClick={() => navigate("/team-list")}
                        className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                      >
                        <i className="fa-solid fa-users mr-2"></i>
                        我的团队
                      </button>
                      <button 
                        onClick={() => navigate("/editor")}
                        className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                      >
                        <i className="fa-solid fa-file-code mr-2"></i>
                        开始编辑
                      </button>
                      <button 
                        onClick={logout}
                        className="block w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700"
                      >
                        <i className="fa-solid fa-right-from-bracket mr-2"></i>
                        退出登录
                      </button>
                    </div>
                  </div>
                </>
              ) : (
                <motion.button 
                  onClick={() => navigate("/login")}
                  className={cn(
                    "px-4 py-2 rounded-md font-medium",
                    isDark 
                      ? "bg-blue-600 hover:bg-blue-700" 
                      : "bg-blue-500 hover:bg-blue-600",
                    "text-white"
                  )}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <i className="fa-solid fa-right-to-bracket mr-2"></i>
                  登录
                </motion.button>
              )}
            </div>
          </div>
        </div>
      </header>

      {/* 主内容区 */}
      <main className="flex-1 container mx-auto p-4 md:p-8">
        <div className="flex flex-col items-center justify-center h-full">
          {/* 欢迎区域 */}
           <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
            className={cn(
              "w-full max-w-4xl p-8 rounded-xl shadow-lg text-center mb-12 backdrop-blur-md",
              isDark ? "bg-gray-800/70 border-gray-700" : "bg-white/80 border-white/20"
            )}
          >
            <motion.h2 
              className="text-4xl font-bold mb-6 bg-gradient-to-r from-blue-500 to-orange-500 bg-clip-text text-transparent"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.2 }}
            >
              欢迎使用API文档系统
            </motion.h2>
            <motion.p 
              className="text-xl mb-8"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.4 }}
            >
              一个简洁高效的API文档管理平台
            </motion.p>
            
            {/* 动态代码展示 */}
            <motion.div
              className={cn(
                "w-full max-w-2xl mx-auto p-4 rounded-lg font-mono text-sm mb-8 text-left overflow-x-auto",
                isDark ? "bg-gray-700" : "bg-gray-100"
              )}
              whileHover={{ scale: 1.02 }}
              transition={{ type: "spring", stiffness: 300 }}
              onClick={showEasterEgg}
            >
              <div className="flex space-x-2 mb-2">
                <div className="w-3 h-3 rounded-full bg-red-500"></div>
                <div className="w-3 h-3 rounded-full bg-yellow-500"></div>
                <div className="w-3 h-3 rounded-full bg-green-500"></div>
              </div>
              <pre className="whitespace-pre-wrap">
                <code className={cn(isDark ? "text-green-400" : "text-green-600")}>
                  {typingText}
                  <span className={cn("ml-1", isDark ? "text-gray-300" : "text-gray-700")}>
                    {isTyping ? "|" : ""}
                  </span>
                </code>
              </pre>
            </motion.div>
            
            {/* 只在未登录时显示登录注册按钮 */}
            {!isAuthenticated && (
              <motion.div 
                className="flex justify-center space-x-4"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: 0.6 }}
              >
                <motion.button
                  onClick={() => navigate("/login")}
                  className={cn(
                    "px-6 py-3 rounded-md font-medium",
                    isDark 
                      ? "bg-blue-600 hover:bg-blue-700" 
                      : "bg-blue-500 hover:bg-blue-600",
                    "text-white"
                  )}
                  whileHover={{ y: -3 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <i className="fa-solid fa-right-to-bracket mr-2"></i>
                  登录
                </motion.button>
                <motion.button
                  onClick={() => setShowRegister(true)}
                  className={cn(
                    "px-6 py-3 rounded-md font-medium",
                    isDark 
                      ? "bg-orange-600 hover:bg-orange-700" 
                      : "bg-orange-500 hover:bg-orange-600",
                    "text-white"
                  )}
                  whileHover={{ y: -3 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <i className="fa-solid fa-user-plus mr-2"></i>
                  注册
                </motion.button>
              </motion.div>
            )}
          </motion.div>

            {/* 产品亮点展示 */}
           <motion.div
              className={cn(
                "w-full max-w-4xl p-6 rounded-xl shadow-lg backdrop-blur-sm",
                isDark ? "bg-gray-800/90" : "bg-white/90"
              )}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.8 }}
            >
              <div className="flex flex-col items-center">
                <h3 className="font-mono text-lg mb-4">产品亮点</h3>
                
                <div className={cn(
                  "w-full grid grid-cols-1 md:grid-cols-2 gap-4",
                  isDark ? "text-gray-200" : "text-gray-800"
                )}>
                  {/* 亮点1 - 高效协作 */}
                  <motion.div
                    whileHover={{ y: -5, scale: 1.02 }}
                    className={cn(
                      "p-4 rounded-lg flex flex-col items-center text-center",
                      isDark ? "bg-gray-700/50" : "bg-gray-100"
                    )}
                  >
                    <div className={cn(
                      "w-16 h-16 rounded-full flex items-center justify-center mb-3",
                      isDark ? "bg-blue-900/50" : "bg-blue-100"
                    )}>
                      <i className="fa-solid fa-bolt text-2xl text-blue-500"></i>
                    </div>
                    <h4 className="font-mono font-bold mb-2">高效协作</h4>
                    <p className="text-sm">团队成员实时协同编辑，提升开发效率</p>
                  </motion.div>

                  {/* 亮点2 - 无缝集成 */}
                  <motion.div
                    whileHover={{ y: -5, scale: 1.02 }}
                    className={cn(
                      "p-4 rounded-lg flex flex-col items-center text-center",
                      isDark ? "bg-gray-700/50" : "bg-gray-100"
                    )}
                  >
                    <div className={cn(
                      "w-16 h-16 rounded-full flex items-center justify-center mb-3",
                      isDark ? "bg-purple-900/50" : "bg-purple-100"
                    )}>
                      <i className="fa-solid fa-plug text-2xl text-purple-500"></i>
                    </div>
                    <h4 className="font-mono font-bold mb-2">无缝集成</h4>
                    <p className="text-sm">与主流开发工具无缝对接，简化工作流程</p>
                  </motion.div>
                </div>
              </div>
            </motion.div>

          {/* 核心功能与统计 */}
          <motion.div 
            className="w-full max-w-6xl"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.8 }}
          >
            <h3 className="text-2xl font-bold text-center mb-8">核心功能</h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {features.map((feature, index) => (
                <motion.div
                  key={index}
                  className={cn(
                    "p-4 rounded-xl shadow-lg",
                    isDark ? "bg-gray-800" : "bg-white"
                  )}
                  whileHover={{ y: -5 }}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.2 * index }}
                >
                  <div className="flex flex-col items-center text-center">
                    <i className={cn(
                      feature.icon,
                      "text-3xl mb-3",
                      isDark ? "text-blue-400" : "text-orange-500"
                    )}></i>
                    <h4 className="text-lg font-bold mb-1">{feature.title}</h4>
                    <p className="text-sm text-gray-500">{feature.description}</p>
                  </div>
                </motion.div>
              ))}
              {/* 更多功能开发中卡片 */}
              <motion.div
                className={cn(
                  "p-4 rounded-xl shadow-lg",
                  isDark ? "bg-gray-800" : "bg-white"
                )}
                whileHover={{ y: -5 }}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.2 * features.length }}
              >
                <div className="flex flex-col items-center text-center">
                  <i className={cn(
                    "fa-solid fa-ellipsis",
                    "text-3xl mb-3",
                    isDark ? "text-blue-400" : "text-orange-500"
                  )}></i>
                  <h4 className="text-lg font-bold mb-1">更多功能</h4>
                  <p className="text-sm text-gray-500">更多功能开发中，敬请期待</p>
                </div>
              </motion.div>
            </div>
          </motion.div>
          {/* 已登录用户显示的内容 */}
          {/* 登录后不再显示“开始编辑”按钮 */}
        </div>
      </main>

      {/* 注册模态框 */}
      {showRegister && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className={cn(
              "w-full max-w-md p-6 rounded-xl shadow-lg",
              isDark ? "bg-gray-800" : "bg-white"
            )}
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className="font-mono font-bold text-xl">用户注册</h2>
              <button
                onClick={() => setShowRegister(false)}
                className={cn(
                  "p-1 rounded-full",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block font-mono text-sm mb-1">用户名</label>
                <input
                  type="text"
                  value={registerForm.userName}
                  onChange={(e) => setRegisterForm({...registerForm, userName: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入用户名"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">账号</label>
                <input
                  type="text"
                  value={registerForm.account}
                  onChange={(e) => setRegisterForm({...registerForm, account: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入账号"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">密码</label>
                <input
                  type="password"
                  value={registerForm.password}
                  onChange={(e) => setRegisterForm({...registerForm, password: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入密码"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">用户头像</label>
                <div className="grid grid-cols-5 gap-2 mb-2">
                  {iconOptions.map(icon => (
                    <motion.button
                      key={icon}
                      onClick={() => setRegisterForm({...registerForm, userIcon: icon})}
                      className={cn(
                        "p-2 rounded-md flex items-center justify-center",
                        registerForm.userIcon === icon 
                          ? (isDark ? "bg-blue-600" : "bg-orange-500") 
                          : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                      )}
                      whileHover={{ scale: 1.1 }}
                    >
                      <i className={cn(
                        icon,
                        "text-xl",
                        registerForm.userIcon === icon ? "text-white" : 
                          (isDark ? "text-blue-400" : "text-orange-500")
                      )}></i>
                    </motion.button>
                  ))}
                </div>
              </div>
              <div className="flex justify-between items-center">
                <button
                  onClick={() => {
                    setShowRegister(false);
                    navigate('/login');
                  }}
                  className={cn(
                    "text-sm font-mono hover:underline",
                    isDark ? "text-blue-400" : "text-blue-500"
                  )}
                >
                  已有账号？去登录
                </button>
                <div className="flex space-x-2">
                  <button
                    onClick={() => setShowRegister(false)}
                    className={cn(
                      "px-4 py-2 rounded-md font-medium",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600" 
                        : "bg-gray-200 hover:bg-gray-300"
                    )}
                  >
                    取消
                  </button>
                  <button
                   onClick={handleRegister}
                   disabled={isRegistering}
                   className={cn(
                     "px-4 py-2 rounded-md font-medium flex items-center justify-center",
                     isDark 
                       ? "bg-blue-600 hover:bg-blue-700" 
                       : "bg-orange-500 hover:bg-orange-600",
                     "text-white",
                     isRegistering ? "opacity-75" : ""
                   )}
                 >
                   {isRegistering ? (
                     <>
                       <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                       注册中...
                     </>
                   ) : (
                     "注册"
                   )}
                  </button>
                </div>
              </div>
            </div>
          </motion.div>
        </div>
      )}
    </div>
  );
}